package com.dcivision.lucene;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.LogFactoryImpl;

public class IndexOptimizeTask extends Thread {
  
  private Log log = new LogFactoryImpl().getInstance(this.getClass());
  
  private long optimizeInterval = 12 * 3600 * 1000; //12H
  
  private long retryInterval = 30000;
  
  public IndexOptimizeTask(long optimizeInterval) {
    super();
    this.optimizeInterval = optimizeInterval;
  }
  
  /**
   * Interval to run the lucene optimize.
   */
  public synchronized void run() {
    while (true) {
      try {
        wait(optimizeInterval);
        while (!IndexFactory.optimize()) {
          wait(retryInterval);
        }
      } catch(InterruptedException e) {
        log.warn("Index optimize task is interrupted.", e);
      } catch (Exception ex) {
        log.error("IndexOptimizeTask fail to optimize.", ex);
      }
    }
  }
  
  /**
   * wake up the run thread to optimize lucene.
   *
   */
  public synchronized void optimize() {
    notifyAll();
  }
}
